package com.module.lemlin.rxhttp

import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.entity.ParameterizedTypeImpl
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.AbstractParser
import rxhttp.wrapper.utils.convert
import java.lang.reflect.Type

@Parser(name = "Response", wrappers = [List::class])
open class HttpServiceParse<T> : AbstractParser<T> {

    protected constructor() : super()

    constructor(type: Type) : super(type)

    override fun onParse(response: okhttp3.Response): T {
        val serviceData: ResponseParse<T> =
            response.convert(ParameterizedTypeImpl[ResponseParse::class.java, mType])

        val data: T? = serviceData.data

        return if (serviceData.code != 200) {
            throw ParseException(
                serviceData.code.toString(), serviceData.msg, response
            )
        } else if (data == null) {
            throw ParseException(
                "10000", serviceData.msg, response
            )
        } else if (data is List<*>) {
            if (data.size == 0) {
                throw ParseException(
                    "20000", serviceData.msg, response
                )
            } else data
        } else data

    }

}

class ResponseParse<T> {
    var code = 0
    var msg: String? = null
    var data: T? = null
}